package com.egao.common.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.remark.entity.TCourseRemark;
import com.egao.common.remark.entity.TReleaseRemark;
import com.egao.common.remark.mapper.TCourseRemarkMapper;
import com.egao.common.remark.mapper.TReleaseRemarkMapper;
import com.egao.common.remark.service.ITReleaseRemarkService;
import com.egao.common.system.entity.UserTwo;
import com.egao.common.system.service.UserTwoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @auther ZhaoPeng Wang
 * @create 2022-03-21 21:52:39
 * @description 服务实现类
 */
@Service
public class TReleaseRemarkServiceImpl extends ServiceImpl<TReleaseRemarkMapper, TReleaseRemark> implements ITReleaseRemarkService {

    @Autowired
   TReleaseRemarkMapper tReleaseRemarkMapper;
    @Autowired
    UserTwoService userTwoService;

    @Override
    public List<TReleaseRemark> getAllReleaseRemark(Integer id) {
        QueryWrapper<TReleaseRemark> wrapper = new QueryWrapper<>();
        wrapper
                .eq("release_id",id)
                .eq("parent_id",0)
                .ne("start",0);
        List<TReleaseRemark> remarkList = tReleaseRemarkMapper.selectList(wrapper);
        for (TReleaseRemark remark : remarkList){
            UserTwo user = userTwoService.getById(remark.getUserId());
            remark.setUsername(user.getUsername());
            remark.setParentUsername("");
            if (remark.getStart() == 2){
                remark.setContent("该评论已被删除");
                remark.setName("该评论已被删除");
            }
            getRemarkTree(remark);
        }

        return remarkList;
    }

    /**
     * 寻找回复的子评论
     * @param parentId
     * @return
     */
    public List<TReleaseRemark> getByParentId(Integer parentId){
        QueryWrapper<TReleaseRemark> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId).ne("start",0);
        return tReleaseRemarkMapper.selectList(wrapper);
    }

    /**
     * 递归获取评论子树
     */
    private void getRemarkTree(TReleaseRemark remark){
        List<TReleaseRemark> res = getByParentId(remark.getId());
        if(res != null){
            for (TReleaseRemark rem : res) {
                UserTwo user = userTwoService.getById(rem.getUserId());
                rem.setUsername(user.getUsername());
                rem.setParentUsername(remark.getUsername());
                if (rem.getStart() == 2){
                    rem.setContent("该评论已被删除");
                    rem.setName("该评论已被删除");
                }
                remark.getChildrenRemarkList().add(rem);
                getRemarkTree(rem);
            }
        }

    }
}
